# -*- coding: utf-8 -*-
import time
import numpy as np
from PIL import ImageGrab
import os

# 配置区
CHECK_INTERVAL = 3
INACTIVITY_THRESHOLD = 15
SCREEN_CHANGE_THRESHOLD = 200000
LOG_FILE = r"screen_activity.log"

# 屏幕分辨率
SCREEN_WIDTH = 1920
SCREEN_HEIGHT = 1080
MONITOR_REGION = (0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 40)  # 忽略底部40像素
# 例如，MONITOR_REGION = (960, 0, 1920, 540) 表示监控右上角四分之一区域。

last_activity_time = time.time()
is_active = True

def log_status(status):
    timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
    log_entry = f"[{timestamp}] 状态: {status}\n"
    with open(LOG_FILE, "a", encoding="gb2312") as f:
        f.write(log_entry)
    print(log_entry.strip())

def check_screen_change():
    global last_activity_time
    try:
        screenshot = ImageGrab.grab(bbox=MONITOR_REGION).convert("L")
        current_frame = np.array(screenshot)
        
        if not hasattr(check_screen_change, "last_frame"):
            check_screen_change.last_frame = current_frame
            return False
        
        diff = np.sum(np.abs(current_frame - check_screen_change.last_frame))
        check_screen_change.last_frame = current_frame
        
        if diff > SCREEN_CHANGE_THRESHOLD:
            last_activity_time = time.time()
            return True
        return False
    except Exception as e:
        print(f"截图失败: {str(e)}")
        return False

def update_status(has_change):
    global is_active, last_activity_time
    current_time = time.time()
    idle_time = current_time - last_activity_time

    if has_change:
        if not is_active:
            log_status("开工")
        is_active = True
        last_activity_time = current_time  # 仅在有实际变化时更新时间
    else:
        if is_active and idle_time > INACTIVITY_THRESHOLD:
            log_status("未开工")
            is_active = False
            # 进入未开工后不再更新时间，维持原最后活动时间
        elif not is_active:
            # 已经处于未开工状态，无需再次处理
            pass


def main():
    global is_active, last_activity_time
    log_status("脚本启动")
    print(f"监控已开始，日志文件路径：{LOG_FILE}")
    
    is_active = True
    last_activity_time = time.time()
    log_status("开工")
    
    try:
        while True:
            has_change = check_screen_change()
            update_status(has_change)
            time.sleep(CHECK_INTERVAL)
    except KeyboardInterrupt:
        log_status("未开工")
        log_status("脚本手动停止")
    except Exception as e:
        log_status(f"脚本异常终止: {str(e)}")

if __name__ == "__main__":
    main()
